# -*- coding:utf-8 -*-

import time
import smtplib
import traceback
from ConfigParser import ConfigParser as Parser
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import COMMASPACE, formatdate

class MailSender():
    def __init__(self, mailConfigFile):
        '''
        检查出错时, 发送给所有相关人员; 每天的汇总邮件, 只发给测试组.
        '''
        self.config = Parser()
        self.config.read(mailConfigFile)
        self._mailHost = self.config.get("mail","mailHost")
        self._mailUser      = self.config.get("mail","mailUser")
        self._mailPassword  = self.config.get("mail","mailPassword")
        self._mailLog       = self.config.get("mail","mailLog")
        self._mailReceivers = ""

    def __currentTime(self):
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))

    def _sendMail(self, title, message):
        try:
            mailMessage            = MIMEMultipart()
            mailMessage['Subject'] = Header(title,"UTF-8")
            mailMessage['From']    = "<" + self._mailUser + ">"
            mailMessage['To']      = ','.join(self._mailReceivers)
            mailMessage['Date']    = formatdate(localtime=True)
            messageTxt             = MIMEText(message,'plain', _charset='UTF-8')
            mailMessage.attach(messageTxt)
            smtp = smtplib.SMTP()
            smtp.connect(self._mailHost)
            smtp.esmtp_features["auth"]="LOGIN"
            smtp.ehlo()
            smtp.starttls()
            smtp.login(self._mailUser, self._mailPassword)
            time.sleep(1)
            smtp.sendmail(self._mailUser, self._mailReceivers, mailMessage.as_string())
            print 'send Mail ok'
            smtp.close()
            open(self._mailLog, "a").write("邮件发送成功:\t 时间: \t %s \nTitle: \t %s \nMessage:\
                                            \t %s \n\n " % (self.__currentTime(), title, message.strip()))
        except Exception, e:
            exceptionString  = traceback.format_exc()
            open(self._mailLog, "a").write("邮件发送异常:\t 时间: \t %s \nTitle: \t %s \nMessage:\
                                            \t %s \n\n %s \n\n" % (self.__currentTime(),         \
                                            title, message.strip(), exceptionString))

    def send_mail_to_team(self, title, body):
        self._mailReceivers = (self.config.get("mail", "teamReceivers")).strip().split(",")
        self._sendMail(title, body)

    def send_mail_to_author(self, title, body):
        self._mailReceivers = (self.config.get("mail", "author")).strip().split(",")
        self._sendMail(title, body)